package com.glink.manage.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glink.manage.domain.UserRoleRelaBean;
import com.glink.manage.mapper.UserRoleRelaMapper;
import com.glink.manage.service.UserRoleRelaService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : qiushaoshan
 * @create 2024/6/22 14:42
 */
@Service
@Slf4j
public class UserRoleRelaServiceImpl extends ServiceImpl<UserRoleRelaMapper, UserRoleRelaBean> implements UserRoleRelaService {


    /**
     * 根据角色ID查询关联的用户ID
     *
     * @param roleId 角色ID
     */
    @Override
    public List<String> findUserIdByRoleId(String roleId) {
        List<String> userIdList = Lists.newArrayList(); 
        if(StringUtils.isBlank(roleId)){
            return userIdList;
        }
        List<UserRoleRelaBean> userRoleRelaBeanList = this.lambdaQuery().eq(UserRoleRelaBean::getRoleId, roleId).list();
        if(CollectionUtils.isNotEmpty(userRoleRelaBeanList)){
            userIdList = userRoleRelaBeanList.stream().map(UserRoleRelaBean::getUserId).collect(Collectors.toList());
        }
        return userIdList;
    }

    /**
     * 根据用户ID获取角色ID
     *
     * @param userId 用户ID
     * @return 角色ID
     */
    @Override
    public List<String> findRoleIdByUserId(String userId) {
        List<String> roleIdList = Lists.newArrayList();
        if(StringUtils.isBlank(userId)){
            return roleIdList;
        }

        List<UserRoleRelaBean> userRoleRelaBeanList = this.lambdaQuery().eq(UserRoleRelaBean::getUserId, userId).list();
        if(CollectionUtils.isNotEmpty(userRoleRelaBeanList)){
            roleIdList = userRoleRelaBeanList.stream().map(UserRoleRelaBean::getRoleId).collect(Collectors.toList());
        }
        return roleIdList;
    }

    /**
     * 根据角色ID删除角色和用户的关系
     *
     * @param roleId 角色ID
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteByRoleId(String roleId) {
        this.lambdaUpdate().eq(UserRoleRelaBean::getRoleId, roleId).remove();
    }
}
